import appStore from '@/store/app'
import appHttp from '@/request/app.js'
import {
	ref
} from 'vue'
/** App基本功能 */
export default class AppSet {
	/**
	 *App启动自测
	 */
	static start() {
		this.getAppInfo()
		// #ifdef APP-PLUS
		//判断是否存在登录信息
		if (!userStore().token) {
			//不存在则跳转登录页
			uni.reLaunch({
				url: "/pages/login/login",
				success: () => {
					//跳转完页面后再关闭启动页
					plus.navigator.closeSplashscreen();
				}
			})
		} else {
			//存在则关闭启动页进入首页
			plus.navigator.closeSplashscreen();
		}
		this.updateApp()
		// #endif
	}
	/** 更新app */
	static async updateApp() {
		// #ifdef APP-PLUS
		const res = await appHttp.upload()
		console.log('运行更新')
		if (!res) return
		const num = ref(0)
		const {
			appName,
			update_content,
			download_url
		} = res;
		uni.showModal({
			title: '更新版本',
			content: update_content,
			cancelText: '取消更新',
			confirmText: '立即更新',
			success: ({
				confirm,
				cancel
			}) => {
				if (confirm) {
					let dtask = plus.downloader.createDownload(
						download_url, {
							force: true
						},
						(d, status) => {
							if (status == 200) {
								let fileSaveUrl = plus.io
									.convertLocalFileSystemURL(d
										.filename);
								plus.runtime.install(fileSaveUrl, {
									force: false
								}, function() {
									uni.showToast({
										title: '更新成功，立即重启',
										icon: 'none'
									})
									setTimeout(() => {
										plus.runtime.restart();
									}, 500)
								}, function(e) {
									console.error('安装失败', e);
								});
							} else {
								//下载失败
								plus.downloader.clear()
								uni.showToast({
									title: '更新失败',
									icon: 'none'
								})
							}
						})
					dtask.start();
					let prg = 0;
					let showLoading = plus.nativeUI.showWaiting("正在下载");
					dtask.addEventListener('statechanged', function(task, status) {
						switch (task.state) {
							case 1:
								showLoading.setTitle("正在下载");
								break;
							case 3:
								prg = parseInt((parseFloat(task.downloadedSize) / parseFloat(task.totalSize)) *
									100);
								showLoading.setTitle("  正在下载" + prg + "%  ");
								break;
							case 4:
								plus.nativeUI.closeWaiting();
								//下载完成  
								break;
						}
					})
				}
			}
		})
		// #endif
	}
	/**获取设备相关信息*/
	static getAppInfo() {
		uni.getSystemInfo({
			success: function(res) {
				console.log('本机信息：', res)
				appStore().setAppInfo(res)
			}
		});
	}
}